package com.tpp.service.impl;

import com.tpp.service.EmailService;
import com.tpp.utils.RedisUtils;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.MailException;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.stereotype.Service;

import java.util.Map;
import java.util.Random;

@Service
public class EmailServiceImpl implements EmailService {

    @Value("${spring.mail.username}")
    private String from;
    @Autowired
    JavaMailSender javaMailSender;
    @Autowired
    RedisUtils redisUtils;
    @RabbitListener(queues = "tpp-cloud-mail")

    public void sendMail(Map map) {
//       1、 从map中获得前端传过来的邮箱
        Object email = map.get("email");

//        2、生成验证码
        Random random = new Random();
        StringBuffer stringBuffer = new StringBuffer();
        for (int i = 0;i<4;i++ ){
            stringBuffer.append(random.nextInt(10));
        }
        String code = stringBuffer.toString();

        //3、生成验证码后，发送验证
        SimpleMailMessage simpleMailMessage = new SimpleMailMessage();
//        3.1验证码
        simpleMailMessage.setText(code);
//        3.2主题
        simpleMailMessage.setSubject("淘票票，注册验证码");
//        3.3发件人
        simpleMailMessage.setFrom(from);
//        3.4收件人
        simpleMailMessage.setTo(email.toString());
//        4发送邮件
        try {
            javaMailSender.send(simpleMailMessage);
            //如果发送成功，记录到redis中
            redisUtils.set(email.toString(),code);
            //设置5分钟过期时间
            redisUtils.expire(email.toString(),60);


        } catch (MailException e) {
            System.out.println(e.getMessage());
        }

    }
}
